package com.lincoln.framework.controller;

import com.lincoln.framework.common.WebUtils;
import com.lincoln.framework.utils.ImageUtils;
import com.lincoln.framework.utils.FileUtilsEx;
import com.lincoln.framework.utils.ParameterChecker;
import com.lincoln.framework.utils.StringUtilsEx;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Base64;

/**
 * 系统端登录controller
 * 
 * @author zwm
 */
@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {
	
	private static final long imageFileSize = 2 * 1024 * 1024;
	
	/**
	 * base64格式的文件上传
	 */
	@RequestMapping("/onBase64.do")
	@ResponseBody
	public void onBase64(HttpServletRequest request, HttpServletResponse response) throws Exception {
		byte[] bytes = Base64.getDecoder().decode(request.getParameter("base64File"));
		String filePath = WebUtils.getTempUploadImgUri() + System.currentTimeMillis();
		File file = new File(StringUtilsEx.getContextPath() + filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(bytes);
		fos.flush();
		fos.close();
		String fileSavePath = filePath + "." + ImageUtils.getType(file);
		File saveFile = new File(StringUtilsEx.getContextPath()  +fileSavePath);
		if (!saveFile.exists()) {
			saveFile.createNewFile();
		}
		FileUtils.copyFile(file, saveFile);
		file.delete();
		if (this.checkFile(saveFile).compareTo("success") != 0) {
			this.returnError(this.checkFile(saveFile));
		} else {
			this.setAttributes("imageUrl", fileSavePath);
			this.returnSuccess();
		}
	}
	
	/**
	 * 图片上传
	 * 
	 * void
	 */
	@RequestMapping("/imageUpload.do")
	@ResponseBody
	public void uploadImage(HttpServletRequest request, HttpServletResponse response) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("image");
			String imageUrl = this.copyFile(file, WebUtils.getTempUploadImgUri());
			this.setAttributes("imageUrl", imageUrl);
			this.returnSuccess();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			this.returnError("上传失败");
		}
	}
	
	/**
	 * 文件上传
	 * 
	 * void
	 */
	@RequestMapping("/fileUpload.do")
	@ResponseBody
	public void fileUpload(HttpServletRequest request, HttpServletResponse response) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			this.setAttributes("fileName", file.getOriginalFilename());
			this.setAttributes("size", file.getSize());
			String fileUrl = this.copyFile(file, WebUtils.getTempUploadImgUri());
			this.setAttributes("fileUrl", fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length()));
			this.returnSuccess();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			this.returnError("上传失败");
		}
	}

	/**
	 * 系统端图片上传(需校验权限)
	 * 
	 * void
	 */
	@RequestMapping("/sysImageUpload.do")
	@ResponseBody
	public void uploadSysImage(HttpServletRequest request, HttpServletResponse response) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("image");
			String imageUrl = this.copyFile(file, WebUtils.getTempSysUploadImgUri());
			this.setAttributes("imageUrl", imageUrl);
			this.returnSuccess();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			this.returnError("上传失败");
		}
	}
	
	/**
	 * 系统端图片上传(需校验权限)
	 * 
	 * void
	 */
	@RequestMapping("/sysFileUpload.do")
	@ResponseBody
	public void uploadSysFile(HttpServletRequest request, HttpServletResponse response) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			this.setAttributes("fileName", file.getOriginalFilename());
			this.setAttributes("size", file.getSize());
			String fileUrl = this.copyFile(file, WebUtils.getTempSysUploadImgUri());
			this.setAttributes("fileUrl", fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length()));
			this.returnSuccess();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			this.returnError("上传失败");
		}
	}

	/**
	 * 保存到目标目录
	 * @throws Exception 
	 */
	public String copyFile(CommonsMultipartFile srcFile, String destDir) throws Exception {
		File destFileDir = new File(StringUtilsEx.getContextPath() + destDir);
		if(!destFileDir.exists()) {
			destFileDir.mkdirs();
		}
		String fileName = srcFile.getOriginalFilename();
		File destFile = new File(StringUtilsEx.getContextPath() + destDir + System.currentTimeMillis());
		srcFile.transferTo(destFile);
		
		String extion = FileUtilsEx.getFileExtension(destFile, fileName);
		fileName = String.valueOf(System.currentTimeMillis());
		if(!ParameterChecker.isNullOrEmpty(extion)) {
			fileName += "." + extion;
		}
		
		FileUtils.copyFile(destFile, new File(StringUtilsEx.getContextPath() + destDir + fileName) );
		
		return destDir + fileName;
	}
	
	/**
	 * 检验文件
	 * 
	 * @return
	 */
	protected String checkFile(File file) throws Exception {
		if (file == null) {
			return "上传文件不能为空！";
		}
		if (file.length() == 0) {
			return "请选择上传文件！";
		}
		if (file.length() > imageFileSize) {
			return "文件大小不能超过2MB！";
		}
		return "success";
	}
	
}
